<template>
  <div>
    <div class="box-title" v-if="isContainer">集装箱车队计划</div>
    <div class="box-title" v-else>件散货车队计划</div>
    <!--  -->

    <div class="form">
      <el-form ref="form" :disabled="see" :model="form" inline label-width="100px" size="small" label-suffix="："
        :rules="rules">
        <el-form-item label="车牌号" prop="carNo">
          <el-select v-model="form.carNo" placeholder="请选择" clearable filterable allow-create @change="carNoChange"
            style="width: 150px">
            <el-option v-for="item in dataList.Car" :key="item.carNo" :label="item.carNo"
              :value="item.carNo"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="isContainer" label="箱号" prop="cntrNo">
          <el-select v-model="form.cntrNo" placeholder="请选择" clearable style="width: 150px" :disabled="cntrNo">
            <el-option v-for="item in dataList.boxlist" :key="item" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-else label="货种" prop="cargoType">
          <el-select v-model="form.cargoTypeName" @change="cargoType" placeholder="请选择" clearable style="width: 150px">
            <el-option v-for="(item, index) in dataList.GoodsType" :key="index" :label="item.name"
              :value="[item.type, item.name]"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="司机" prop="driver">
          <el-select v-model="form.driverDetail" @change="driverChange" placeholder="请选择" clearable style="width: 150px"
            remote filterable :remote-method="remoteMethod">
            <el-option v-for="(item, index) in dataList.driverList" :key="index" :label="item.driver"
              :value="[item.driver, item.driverTel, item.certNumber]"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系方式" prop="driverTel">
          <el-input v-model="form.driverTel" placeholder="请输入" clearable style="width: 150px">
          </el-input>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="form.certNumber" placeholder="请输入" clearable style="width: 150px">
          </el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- -->
    <div class="btn">
      <el-button type="primary" size="small" style="background-color: #043aa7" :loading="butLoading" v-if="!see"
        @click="addGood">新增</el-button>
      <!-- <el-button type="primary" size="small" style="background-color:#043AA7" :loading="butLoading" v-if="!see"
        @click="importProject">导入</el-button> -->
      <!-- <el-button type="primary" size="small" v-if="!see" :loading="butLoading" style="background-color:#043AA7"
        @click="save">提交计划</el-button> -->
      <el-upload class="upload" action="" :show-file-list="false" :httpRequest="importProject" accept=".xlsx,.xls">
        <el-button type="primary" class="" size="small" style="background-color: #043aa7" :loading="butLoading"
          v-if="!see">导入<!-- 并提交计划 --></el-button>
      </el-upload>
      <el-button type="primary" size="small" v-if="!see" :loading="butLoading" style="background-color: #043aa7"
        @click="downLoadExcel">模板下载</el-button>
    </div>
    <div class="table">
      <div class="box-title">
        <span>车队列表</span>
        <!-- <el-button type="primary" size="small" v-if="!see" :loading="butLoading" style="background-color:#043AA7" @click="deleteCarTeam">删除</el-button> -->
      </div>
      <el-table :data="tableData" :header-cell-style="{ background: '#EEF1F5' }" style="width: 100%">
        <el-table-column type="index" label="序号" min-width="40">
        </el-table-column>
        <el-table-column prop="carNo" label="车牌号" min-width="120">
        </el-table-column>
        <el-table-column v-if="isContainer" prop="cntrNo" label="箱号" min-width="120">
        </el-table-column>
        <el-table-column v-else prop="cargoName" label="货种" min-width="120">
        </el-table-column>
        <el-table-column prop="driver" label="司机" min-width="120">
        </el-table-column>
        <el-table-column prop="driverTelNick" label="联系方式" min-width="140">
        </el-table-column>
        <el-table-column prop="certNumberNick" label="身份证号" min-width="140">
        </el-table-column>
        <el-table-column prop="createUserName" label="创建人" min-width="180">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="100">
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="120" align="center">
          <template slot-scope="scope">
            <el-button @click="del(scope.row, scope.$index)" v-if="!see" type="text"
              style="color: #ff3838">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import moment from "moment";
export default {
  name: "",
  components: {},
  props: ["isContainer", "planNo", "cstCstmcd", "see", "cntrNo", "type"],
  data() {
    return {
      butLoading: false,
      headers: { "Content-Type": "multipart/form-data;charset=UTF-8" },
      form: {
        cntrNo: this.cntrNo ? "*" : null,
      },
      rules: {
        carNo: [{ required: true, message: "请选择车牌号", trigger: "change" }],
        cntrNo: [{ required: true, message: "请选择箱号", trigger: "change" }],
        cargoType: [
          { required: true, message: "请选择货种", trigger: "change" },
        ],
        driver: [{ required: true, message: "请选择司机", trigger: "change" }],
        driverTel: [
          {
            required: true,
            message: "请输入联系方式",
            trigger: ["blur", "change"],
          },
        ],
      },
      tableData: [],
      cadList: [],
      boxlist: [],
      dataList: {},
      personInfo: {},
    };
  },
  watch: {
    planNo() {
      if (this.isContainer) {
        this.queryWithCntr();
      } else {
        this.queryWithCargo();
      }
    },
  },
  methods: {
    downLoadExcel() {
      console.log(this.type, "我是type");
      let params = {};
      if (this.type == "goods") {
        // window.open('https://ebsnsp.com:20080/app-release/file/jxgw/src/template/件散货车队计划导入模板.xlsx','_blank');
        params = {
          schedulesType: "BULK_CARGO",
        };
      } else if (this.type == "boxGoods") {
        // window.open('https://ebsnsp.com:20080/app-release/file/jxgw/src/template/集装箱车队计划导入模板.xlsx','_blank')
        params = {
          schedulesType: "CONTAINER",
        };
      }
      this.$api
        .getTemplate(params)
        .then((res) => {
          // console.log(res, "===========================");
          const content = res;
          const blob = new Blob([content]); // 构造一个blob对象来处理数据
          const link = document.createElement("a"); // 创建a标签
          link.download = "车队计划模板.xls"; // a标签添加属性
          link.style.display = "none";
          link.href = URL.createObjectURL(blob);
          document.body.appendChild(link);
          link.click(); // 执行下载
          URL.revokeObjectURL(link.href); // 释放url
          document.body.removeChild(link); // 释放标签
        })
        .catch((e) => {
          console.log(e);
        });
    },
    cargoType(type) {
      console.log(type);
      this.form.cargoType = type[0];
      this.form.cargoName = type[1];
      // let that=this
      // this.dataList.GoodsType.forEach(item=>{
      //   if(type == item.type){
      //     that.form.cargoName=item.name
      //   }
      // })
    },
    driverChange(type) {
      console.log(type);
      this.form.driver = type[0];
      this.form.driverTel = type[1];
      this.form.certNumber = type[2];
    },
    del(row, index) {
      console.log(row, index);
      // this.tableData.splice(index, 1)
      this.$confirm("确认删除此数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let params = {
            id: row.id,
            truckCompanyCode: this.cstCstmcd,
          };
          this.butLoading = true;
          this.$api
            .deleteTruckPlan(params)
            .then((res) => {
              if (res.success) {
                this.$message.success("删除成功");
                if (this.isContainer) {
                  this.queryWithCntr();
                } else {
                  this.queryWithCargo();
                }
              }
            })
            .catch((err) => {
              console.log("error", err);
            })
            .finally(() => {
              this.butLoading = false;
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    save() {
      this.butLoading = true;
      if (0 === this.tableData.length) {
        this.$message.error("请先填写计划数据");
        this.butLoading = false;
        return;
      }
      let par = {
        businessType: this.isContainer ? "CONTAINER" : "BULK_CARGO",
        planNo: this.planNo,
        truckCarList: this.tableData,
        truckCompanyCode: this.cstCstmcd,
      };
      this.$api
        .planTruckCarSubmit(par)
        .then((res) => {
          if (200 === res.code) {
            this.$message.success("提交成功！");
            this.tableData = [];
            this.form = {};
            this.$refs.form.resetFields();
            this.$emit("close");
          } else {
            this.butLoading = false;
            this.$message.error(err.message);
          }
        })
        .catch((res) => {
          this.butLoading = false;
          this.$message.error(err.message);
        });
    },
    deleteCarTeam() { },
    addGood() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.form.driverTelNick = this.form.driverTel;
          this.form.certNumberNick = this.form.certNumber;
          this.form.createUserName = this.personInfo.name;
          this.form.createTime = moment(new Date()).format("YYYY-MM-DD");
          // this.tableData.push(JSON.parse(JSON.stringify(this.form)))
          let temp = JSON.parse(JSON.stringify(this.form));
          let params = {
            businessType: this.isContainer ? "CONTAINER" : "BULK_CARGO",
            planNo: this.planNo || "",
            carNo: temp.carNo || "",
            cntrNo: temp.cntrNo || "",
            cargoType: temp.cargoType || "",
            driver: temp.driver || "",
            driverTel: temp.driverTel || "",
            certNumber: temp.certNumber || "",
            truckCompanyCode: this.cstCstmcd || "",
          };
          this.butLoading = true;
          this.$api
            .insertTruckPlan(params)
            .then((res) => {
              if (res.success) {
                this.$message.success("新增成功");
                if (this.isContainer) {
                  this.queryWithCntr();
                } else {
                  this.queryWithCargo();
                }
                /* 重置表单数据 */
                this.form = {};
                if (this.cntrNo) {
                  this.form.cntrNo = "*";
                }
                this.$refs.form.resetFields();
              }
            })
            .catch((err) => {
              console.log("error", err);
            })
            .finally(() => {
              this.butLoading = false;
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    /* 车队计划导入 */
    importProject(para) {
      let FormDatas = new FormData(); //声明一个FormDate对象
      FormDatas.append("file", para.file); //把文件信息放入对象中
      FormDatas.append("planNo", this.planNo); //计划号
      FormDatas.append(
        "businessType",
        this.isContainer ? "CONTAINER" : "BULK_CARGO"
      ); //委托类型(BULK_CARGO件散货,CONTAINER集装箱)
      FormDatas.append("truckCompanyCode", this.cstCstmcd); //车队单位
      this.butLoading = true;
      this.$api
        .importTruckPlan(FormDatas)
        .then((res) => {
          if (res.success) {
            this.$message.success("导入成功");
            if (this.isContainer) {
              this.queryWithCntr();
            } else {
              this.queryWithCargo();
            }
          }
        })
        .catch((err) => {
          console.log("error", err);
        })
        .finally(() => {
          this.butLoading = false;
        });
    },
    remoteMethod(key) {
      console.log("选择框输入内容", key);
      this.$set(this.form, "driver", key);
      this.$set(this.form, "driverTel", "");
      this.$set(this.form, "certNumber", "");
      this.$set(this.form, "driverDetail", key);
    },
    //车牌号查询
    queryCar() {
      this.$api
        .queryCar({
          startpage: 1,
          pagesize: 999,
          customerCode: this.personInfo.customerCode,
        })
        .then((res) => {
          this.$set(this.dataList, "Car", res.data);
        })
        .catch();
    },
    //货种查询
    queryGoodsType() {
      this.$api
        .queryGoodsType({
          planNo: this.planNo,
        })
        .then((res) => {
          this.$set(this.dataList, "GoodsType", res.data);
          //this.dataList.GoodsType=res.data
        })
        .catch();
    },
    carNoChange(val) {
      this.$set(this.form, "driver", "");
      this.$set(this.form, "driverTel", "");
      this.$set(this.form, "certNumber", "");
      this.$set(this.form, "driverDetail", "");
      if (val) {
        this.queryDriverList(val);
      } else {
        this.$set(this.dataList, "driverList", []);
      }
    },
    // 司机查询
    queryDriverList(val) {
      this.$api
        .queryDriverList({
          carNo: val,
        })
        .then((res) => {
          this.$set(this.dataList, "driverList", res.data);
        })
        .catch();
    },
    //箱号查询
    queryCntrnoByPlanNo() {
      this.$api
        .queryCntrnoByPlanNo({
          planNo: this.planNo,
        })
        .then((res) => {
          this.$set(this.dataList, "boxlist", res.data);
          //this.dataList.GoodsType=res.data
        })
        .catch();
    },
    //件散货-车队计划查询带货种名称
    queryWithCargo() {
      this.$api
        .queryWithCargo({
          planNo: this.planNo,
        })
        .then((res) => {
          //this.dataList.Cargo=res.data
          this.tableData = res.data;
        })
        .catch();
    },
    //集装箱-车队计划查询
    queryWithCntr() {
      this.$api
        .queryWithCntr({
          planNo: this.planNo,
        })
        .then((res) => {
          //this.dataList.Cntr=res.data
          this.tableData = res.data;
        })
        .catch();
    },
    init() {
      this.personInfo = JSON.parse(localStorage.getItem("userInfo"));
      this.queryCar();
      this.queryGoodsType();
      this.queryCntrnoByPlanNo();
      if (this.isContainer) {
        this.queryWithCntr();
      } else {
        this.queryWithCargo();
      }
    },
  },

  computed: {},

  mounted() {
    this.init();
  },
};
</script>
<style lang='scss' scoped>
.form {
  display: flex;
  justify-content: center;
  width: 100%;
}

.box-title {
  font-size: 18px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  color: #333333;
  // line-height: 16px;
  // line-height: 20px;
  padding-left: 10px;
  border-left: 5px solid #4980d5;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.btn {
  margin-top: 30px;
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #d7d7d7;
  text-align: center;
  display: flex;
  justify-content: center;

  .el-button {
    width: 80px;
    margin-right: 30px;
  }

  .longBtn {
    width: 120px;
  }
}
</style>
